package com.abacus.pos.base

import android.app.Dialog
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import com.abacus.pos.App
import com.abacus.pos.R
import com.abacus.pos.ext.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import me.jessyan.autosize.AutoSizeConfig


abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity() {

    /*指定xml文件*/
    abstract fun getLayoutResource(): Int

    /*在这个方法中实现viewmodel的初始化 */
    abstract fun initVM()

    /* 在这个方法里实现数据初始化动作*/
    abstract fun startObserve()

    abstract fun onPortrait()

    abstract fun onLandScape()

    /*获取fragment容器id*/
    abstract fun getContainId(): Int


    lateinit var binding: T
    private var dialog: Dialog? = null
    val handler = Handler(Looper.getMainLooper())
    private val isLand by lazy {
        resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
    }
    private val mainScope = MainScope()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, getLayoutResource())
        binding.lifecycleOwner = this
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
        initVM()
        startObserve()
        if (isLand) {
            onLandScape()
        } else {
            onPortrait()
        }
    }


    /**
     * 切换fragment
     * containerViewId
     * fragmet
     * addToBackStack 是否加入回退栈
     * clearStack 是否清空回退栈
     */
    fun switchFragment(
        fragment: Fragment,
        addToBackStack: Boolean = true,
        clearStack: Boolean = false
    ) {
        handler.post {
            if (clearStack && !supportFragmentManager.isStateSaved) {
                supportFragmentManager.popBackStackImmediate(
                    null,
                    FragmentManager.POP_BACK_STACK_INCLUSIVE
                )
            }
            val transaction = supportFragmentManager.beginTransaction()
            transaction.replace(getContainId(), fragment, fragment::class.java.name)
            if (addToBackStack) {
                transaction.addToBackStack(fragment::class.java.name)
            }
            transaction.commitAllowingStateLoss()
            supportFragmentManager.executePendingTransactions()
        }

    }


    /**
     * 显示toast弹窗
     */
    fun showToast(msg: String?, duration: Int = Toast.LENGTH_SHORT) {
        if (msg.isNullOrEmpty()) return
        mainScope.launch(Dispatchers.Main) {
            this@BaseActivity.toast(msg, duration)
        }
    }

    /**
     * 显示toast弹窗
     */
    fun showToast(@StringRes id: Int, duration: Int = Toast.LENGTH_SHORT) {
        mainScope.launch(Dispatchers.Main) {
            this@BaseActivity.toast(id)
        }
    }


    /**
     * 展示等待层
     */
    fun showDialog() {
        mainScope.launch(Dispatchers.Main) {
            dialog?.apply {
                dialog = Dialog(this@BaseActivity)
                setContentView(R.layout.dialog_loading)
                setCanceledOnTouchOutside(false)
                window?.setDimAmount(0.6f)
                window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
                window?.setBackgroundDrawableResource(R.color.transpant)
            }
            if (dialog?.isShowing == true) return@launch
            dialog?.show()
        }
    }

    /**
     * 隐藏等待层
     */
    fun hideDialog() {
        mainScope.launch(Dispatchers.Main) {
            if (dialog?.isShowing == true) {
                dialog?.dismiss()
            }
        }
    }

    override fun onBackPressed() {
        val backStackEntryCount: Int = supportFragmentManager.backStackEntryCount
        if (backStackEntryCount <= 1) {
            finish()
            return
        }
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
        mainScope.cancel()
    }
}
